package uestc.lj.gulishop.product.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import uestc.lj.common.exception.ErrorCode;
import uestc.lj.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一处理异常类
 *
 * @author crazlee
 */
@Slf4j
@RestControllerAdvice(basePackages = "uestc.lj.gulishop.product.controller")
public class GuliShopException {

    /**
     * 处理校验数据异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();

        Map<String, String> map = new HashMap<>();
        // 获取校验的错误结果
        result.getFieldErrors().forEach((item) -> {
            // 获取错误提示
            String message = item.getDefaultMessage();
            // 获取出错的属性的名字
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(ErrorCode.VALID_EXCEPTION.getCode(), ErrorCode.VALID_EXCEPTION.getMessage()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(ErrorCode.UNKONW_EXCEPTION.getCode(), ErrorCode.UNKONW_EXCEPTION.getMessage());
    }
}
